using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Caliburn.Micro;

namespace SimpleQueryTool.Library.Data
{
    public class LoadDataResult<T> : IResult
    {
        private readonly string _connectionString;
        private readonly Action<IList<DataRow>> _onSuccess;
        private readonly string _query;

        public LoadDataResult(string query, string connectionString, Action<IList<DataRow>> onSuccess)
        {
            _query = query;
            _connectionString = connectionString;
            _onSuccess = onSuccess;
        }

        public void Execute(ResultExecutionContext context)
        {
            using (var connection = new SqlConnection(_connectionString))
            {
                var command = new SqlCommand(_query, connection);
                connection.Open();

                SqlDataReader reader = command.ExecuteReader();
                
                var dataTable = new DataTable();
                dataTable.Load(reader);
                var dataRows = dataTable.AsEnumerable().ToList();

                reader.Close();
                Caliburn.Micro.Execute.OnUIThread(() => _onSuccess(dataRows));
                Completed(this, new ResultCompletionEventArgs());
            }
        }

        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
    }
}